<template>
  <div class="question-list-container">
    <!-- 搜索与发布区域 -->
    <el-card shadow="hover" class="search-card">
      <el-input
          v-model="searchQuery"
          placeholder="搜索心理相关问题..."
          :prefix-icon="Search"
          @keyup.enter="searchQuestions"
      />
      <el-button type="primary" @click="searchQuestions">搜索</el-button>
      <el-button type="success" @click="goToPostQuestion">发布问题</el-button>
    </el-card>

    <!-- 问题列表卡片 -->
    <el-card
        v-for="question in questions"
        :key="question.id"
        shadow="hover"
        class="question-card"
        @click="goToQuestionDetail(question.id)"
    >
      <h3>{{ question.title }}</h3>
      <p class="question-content">{{ question.content }}</p>
      <div class="question-meta">
        <span>{{ question.author.name }}</span>
        <span>{{ formatTime(question.createdAt) }}</span>
        <el-tag>{{ question.category }}</el-tag>
        <el-tag>{{ question.answersCount }} 个回答</el-tag>
      </div>
    </el-card>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="fetchQuestions"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const router = useRouter()
const questions = ref<any[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取问题列表
const fetchQuestions = async () => {
  try {
    const res = await axios.get('/api/questions', {
      params: { page: currentPage.value, size: pageSize.value, query: searchQuery.value }
    })
    questions.value = res.data.data
    total.value = res.data.total
  } catch (err) {
    ElMessage.error('获取问题列表失败，请稍后再试')
    console.error(err)
  }
}

// 搜索问题
const searchQuestions = () => {
  currentPage.value = 1
  fetchQuestions()
}

// 跳转到问题详情
const goToQuestionDetail = (id: number) => {
  router.push({ name: 'QuestionDetail', params: { id } })
}

// 跳转到发布问题（示例：实际需对接发布组件）
const goToPostQuestion = () => {
  router.push({ name: 'PostQuestion' })
}

// 简单格式化时间（实际推荐dayjs库）
const formatTime = (time: string) => new Date(time).toLocaleString()

onMounted(() => fetchQuestions())
</script>

<style scoped>
.question-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.search-card {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}
.question-card {
  cursor: pointer;
  margin-bottom: 15px;
}
.question-content {
  margin: 10px 0;
  line-height: 1.6;
}
.question-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #666;
  font-size: 14px;
}
</style>